package com.fingard.dsp.bank.directbank.cmb05;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.google.gson.Gson;
import net.sf.json.JSONArray;

import java.sql.Connection;
import java.util.*;

/**
 * @ClassName CMB05Transaction
 * @Author Zhengzy
 * @Date 2020/3/26 15:06
 * @Version 1.0
 **/
public class CMB05Transaction extends CMB05Base implements ITransaction {
    // 明细查询会用到账号-户口号
    private static final String INSERTRECEIPT = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,REQSEQID,BANKREQSEQID) values (?,?,?,?);";
    private static final String SELECTRECEIPT = "SELECT BANKREQSEQID FROM REQSEQIDMAPPING WHERE REQSEQID=? and BANKCODE=?;"; // 账号=？，bankcode=？

    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();
        Connection conn = FGBiz.getLocalDbConn();

        // 先查看这个账号对应的户口号存在不存在
        // 户口号是否被存了
        Map<String, Object> map = JDBCHelper.execQuerySingle(conn, SELECTRECEIPT, new Object[]{p_req7516.actNum, p_req7516.reqHeader.bankCode});
        if (map.size() == 0) {
            // 没有存该账号和对应的户口号，先进行一次查询操作
            getEacnbr(p_req7516);
        }
        String actnbr = "";// 客户户口号
        // 判断是否插入客户号成功
        Map<String, Object> afterMap = JDBCHelper.execQuerySingle(conn, SELECTRECEIPT, new Object[]{p_req7516.actNum, p_req7516.reqHeader.bankCode});
        if (afterMap.size() == 0) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo("客户户口号不存在");
            retAts.writeEnd();
            return retAts;
        } else {
            actnbr = afterMap.get("BANKREQSEQID").toString();// 取出客户户口号
        }
        // 组装报文
        StringBuffer sbf = new StringBuffer();
        CMB05Header bankHeader = new CMB05Header();
        bankHeader.transCode = "FMTRSDTN";
        // 组装请求前缀
        writeCommonHeader(sbf, bankHeader);
        // 组装请求报文体json
        JSONObject json = new JSONObject();
        HashMap<String, Object> requestMap = new HashMap<String, Object>();
        HashMap<String, String> headMap = new HashMap<String, String>();
        HashMap<String, Object> bodyMap = new HashMap<String, Object>();
        bodyMap.put("eacnbr", p_req7516.actNum);// 客户户口	eacnbr	String(35)	Y	可通过6.1.1接口查询
        bodyMap.put("actnbr", actnbr);// 账号
        bodyMap.put("bgndat", Format.Date10Format.format(Format.Date8Format.parse(p_req7516.dateFrom)));// 起始日期 yyyy-MM-dd格式
        bodyMap.put("enddat", Format.Date10Format.format(Format.Date8Format.parse(p_req7516.dateTo)));// 结束日期 yyyy-MM-dd格式
        bodyMap.put("qrynum", getBankConfig().getValueAsString("qrynum"));// 每次查询笔数
        bodyMap.put("ctnkey", "");// 续传标志
        requestMap.put("body", bodyMap);
        headMap.put("funcode", bankHeader.transCode);
        headMap.put("userid", bankFront.loginName);
        requestMap.put("head", headMap);
        json.put("request", requestMap);
        sbf.append(JSON.toJSONString(json));

        int firstReq = 1;// 用来判断是否续传
        while (firstReq == 1) {
            // 发送到银行
            String[] tmpStrRet = sendToBank(sbf.toString());
            if (tmpStrRet[0].length() == 0) {
                // 把结果转成json
                JSONObject response = JSON.parseObject(tmpStrRet[1]);
                if (response != null) {
                    String info = response.getString("response");
                    JSONObject content = JSON.parseObject(info);
                    String head = content.getString("head");
                    String body = content.getString("body");
                    Gson gson = new Gson();
                    Map<String, String> headInfo = new HashMap<String, String>();
                    headInfo = gson.fromJson(head, headInfo.getClass());
                    if (headInfo != null) {
                        String responseCode = headInfo.get("resultcode");
                        String responseMsg = headInfo.get("resultmsg");
                        if ("SUC0000".equals(responseCode)) {
                            JSONObject bodyInfos = JSON.parseObject(body);
                            String args = bodyInfos.getString("trsdtl");// 交易明细list
                            String ctnkey = bodyInfos.getString("ctnkey");// 续传标志区域
                            Map<String, String> ctnkeyInfo = new HashMap<String, String>();
                            ctnkeyInfo = gson.fromJson(ctnkey, ctnkeyInfo.getClass());
                            String ctntag = "";// N代表没有续传，Y时将ctnkey内容原样放入请求报文中的ctnkey里面进行续传。
                            if ("null".equals(ctnkey) || StringHelper.isNullOrEmpty(ctnkey)) {
                            } else {
                                ctntag = ctnkeyInfo.get("ctntag");
                            }
                            if ("Y".equals(ctntag)) {
                                // 修改原报文，用于再次请求
                                sbf = new StringBuffer();
                                writeCommonHeader(sbf, bankHeader);
                                bodyMap.remove("ctnkey");
                                bodyMap.put("ctnkey", ctnkey);
                                requestMap.remove("body");
                                requestMap.put("body", bodyMap);
                                json.put("request", requestMap);
                                sbf.append(JSON.toJSONString(json));
                            } else {// 不需要续传
                                firstReq = 0;
                            }
                            // 不管是否续传，都把本次返回的数据处理
                            JSONArray array = JSONArray.fromObject(args);
                            for (int i = 0; i < array.size(); i++) {
                                RetAtsTransDetail detail = new RetAtsTransDetail();
                                String record = array.getString(i);
                                Map<String, String> recordInfo = new HashMap<String, String>();
                                recordInfo = gson.fromJson(record, recordInfo.getClass());
                                detail.actNum = p_req7516.actNum;// 客户账号
                                detail.accBal = recordInfo.get("onlbal");;// 账户余额
                                detail.cur = convertCurToATS(recordInfo.get("ccynbr"));// 币种
                                String date = recordInfo.get("valdat");// 起息日
                                detail.valueDate = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8);
                                String tranDate = recordInfo.get("trsdat");// 交易日期
                                detail.tranDate = tranDate.substring(0, 4) + "-" + tranDate.substring(4, 6) + "-" + tranDate.substring(6, 8);
                                detail.tranTime = detail.tranDate + " 00:00:00";
                                detail.usage = recordInfo.get("txtclt");// 摘要
                                detail.recAccNum = recordInfo.get("relacc");// 对手方账户
                                detail.recAccName = recordInfo.get("relnam");// 对手方户名
                                detail.recAccBank = recordInfo.get("relbnk");// 对手方银行
                                String cdFlag = recordInfo.get("trsdir");// 借D,贷C
                                String tranAmt = recordInfo.get("trsamt").replace("-", "");// 交易金额
                                if ("C".equals(cdFlag)) {
                                    // 贷
                                    if (tranAmt.indexOf(-1) != -1) { // 是负数
                                        detail.cdFlag = "1";
                                    } else {
                                        detail.cdFlag = "2";
                                    }
                                } else if ("D".equals(cdFlag)) {
                                    // 借
                                    if (tranAmt.indexOf(-1) != -1) {
                                        detail.cdFlag = "2";
                                    } else {
                                        detail.cdFlag = "1";
                                    }
                                }
                                detail.tranAmt = tranAmt.replace("-", "");// 交易金额
                                // 添加查询结果
                                retAts.writeRetDetail(detail);
                            }

                        } else {
                            firstReq = 0;
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo(responseMsg);
                        }
                    }
                } else {
                    firstReq = 0;
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo("请求未正常返回");
                }
            } else {
                firstReq = 0;
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpStrRet[1]);
            }
        }
        conn.close();
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        p_req7516.actArea = p_req7515.actArea;
        Date date = new Date();
        p_req7516.dateFrom = Format.Date8Format.format(date);
        p_req7516.dateTo = Format.Date8Format.format(date);
        return d_7516_HisTrans(p_req7516);
    }

    /**
     * 进行余额查询，获得actnbr
     */
    public void getEacnbr(Req7516HisTrans p_req7516) throws Exception {
        Connection conn = FGBiz.getLocalDbConn();
        StringBuffer sbf = new StringBuffer();
        CMB05Header bankHeader = new CMB05Header();
        bankHeader.transCode = "DCDACCYE";
        // 组装请求前缀
        writeCommonHeader(sbf, bankHeader);
        // 组装请求报文体json
        JSONObject json = new JSONObject();
        HashMap<String, Object> requestMap = new HashMap<String, Object>();
        HashMap<String, String> headMap = new HashMap<String, String>();
        headMap.put("funcode", bankHeader.transCode);
        headMap.put("userid", bankFront.loginName);
        requestMap.put("head", headMap);
        HashMap<String, Object> bodyMap = new HashMap<String, Object>();
        bodyMap.put("ctnkey", "");// 第一次传空 如返回报文有该字段 则将值赋到请求报文中
        requestMap.put("body", bodyMap);
        json.put("request", requestMap);
        sbf.append(JSON.toJSONString(json));

        // 发送到银行
        String[] tmpStrRet = sendToBank(sbf.toString());
        if (tmpStrRet[0].length() == 0) {
            // 把结果转成json
            JSONObject response = JSON.parseObject(tmpStrRet[1]);
            if (response != null) {
                String info = response.getString("response");
                JSONObject content = JSON.parseObject(info);
                String head = content.getString("head");
                String body = content.getString("body");
                Gson gson = new Gson();
                Map<String, String> headInfo = new HashMap<String, String>();
                Map<String, String> bodyInfo = new HashMap<String, String>();
                headInfo = gson.fromJson(head, headInfo.getClass());
                if (headInfo != null) {
                    String responseCode = headInfo.get("resultcode");
                    if ("SUC0000".equals(responseCode)) {
                        JSONObject bodyInfos = JSON.parseObject(body);
                        String args = bodyInfos.getString("actlis");
                        JSONArray array = JSONArray.fromObject(args);
                        for (int i = 0; i < array.size(); i++) {
                            String record = array.getString(i);
                            Map<String, String> recordInfo = new HashMap<String, String>();
                            recordInfo = gson.fromJson(record, recordInfo.getClass());
                            String actnbr = recordInfo.get("actnbr");// 账号
                            String eacnbr = recordInfo.get("eacnbr");// 户口号，需要同账号存储起来，用于明细查询
                            // 没有存该账号和对应的户口号，入库
                            Map<String, Object> map = JDBCHelper.execQuerySingle(conn, SELECTRECEIPT, new Object[]{eacnbr, p_req7516.reqHeader.bankCode});
                            if (map.size() == 0) {
                                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                                // 没有存该账号和对应的户口号，入库
                                JDBCHelper.update(conn, INSERTRECEIPT, new Object[]{uuid, p_req7516.reqHeader.bankCode, eacnbr, actnbr});
                            }
                        }
                    }
                }
            }
        }
        conn.close();
    }
}
